<?php
namespace app\model;

use think\Model;
use app\model\ReturnedMoney;
/**
 * @mixin think\Model
 */
class Customer extends Model
{
   
    //关联模型
    public function users()
    {
        return $this->belongsTo('user','user_id')->bind(['username']);
    }
    
    
    //列表
    public function get_list($name=0,$p=0){
        if($name){
            $wh[] = ['name','like','%'.$name.'%'];
        }
        if(session('info.is_leader') != 1 && session('info.role_id') !=1 ){
            $wh[] = ['user_id','=',session('uid')];
        }
        $wh[] = ['status','=',1];
        $arr['list'] = $this->with('users')
            ->where($wh)
            ->order("create_time desc")->page($p['page']*1,$p['limit']*1)->select(); 
        foreach ($arr['list'] as $k=>$v){ 
            $arr['list'][$k]['delivery'] = $this->get_delivery_num($v['id']);
        }
        $arr['con'] = $this->with('users')->where($wh)->count('id');
        return $arr; 
    }
    //客户 再投/总计投递
    function get_delivery_num($cu_id){
        $wh["status"] = 1;
        $wh["customer_id"] = $cu_id;
        $total_num = Items::where($wh)->count('id');
        $wh["is_deliver"] = 1;
        $in_num = Items::where($wh)->count('id');
        return $in_num.'/'.$total_num;
    }
    
    
    //添加
    public function get_add($data){
        $validate = \think\facade\Validate::rule([
            'user_id|媒介工作人员'  => 'require',
            'name|客户姓名'  => 'require|max:50|unique:customer',
            'mobile|客户手机号'  => 'regex:/^1[34578]\d{9}$/'
        ]);
    
        if(!$validate->check($data)){
            // 验证失败 输出错误信息
            return $validate->getError();
        }else{
            $data['oper_name'] = session('info.username');
            return $this->save($data);
        }
    
    }
    //修改
    public function get_save($data){
        $validate = \think\facade\Validate::rule([
            'user_id|媒介工作人员'  => 'require',
            'name|客户姓名'  => 'require|max:50',
            'mobile|客户手机号'  => 'regex:/^1[34578]\d{9}$/'
        ]);
    
        if(!$validate->check($data)){
            // 验证失败 输出错误信息
            return $validate->getError();
        }else{
            $data['oper_name'] = session('info.username');
            $data['update_time'] = time();
            return $this->where('id',$data['id'])->save($data);
    
        }
    
    }
    
    
    
   //根据账户id 获取客户信息
   function get_acc_cu_info($acc_id){
       $wh[] = ["acc_id",'like','%'.$acc_id.'%'];
       $name = $this->field('id,name')->where($wh)->find();
       
       return $name;
   }
    
    //搜索获取客户列表
    public function get_search_cu_list(){
        if(session('info.is_leader') != 1 && session('info.role_id') !=1 ){
            $wh[] = ['user_id','=',session('uid')];
        }
        $wh[] = ['status','=',1];
        return $this->field('id,name')->where($wh)->select();
    }
    
    
    
    
}
